package com.woniu.sharepark.propertysystem.controller;


import com.github.pagehelper.PageInfo;
import com.woniu.sharepark.common.JsonResult;
import com.woniu.sharepark.common.pojo.Login;
import com.woniu.sharepark.leasesystem.common.pojo.CarParkComment;
import com.woniu.sharepark.leasesystem.common.pojo.OrderForm;
import com.woniu.sharepark.leasesystem.common.service.CarParkCommentService;
import com.woniu.sharepark.leasesystem.common.service.OrderFormService;
import com.woniu.sharepark.leasesystem.lessor.pojo.CarPark;
import com.woniu.sharepark.leasesystem.lessor.service.CarParkService;
import com.woniu.sharepark.leasesystem.tenant.pojo.Car;
import com.woniu.sharepark.leasesystem.tenant.service.CarService;
import com.woniu.sharepark.platformsystem.log.annonation.BackgroundLogAnnotation;
import com.woniu.sharepark.platformsystem.service.ScaleService;
import com.woniu.sharepark.platformsystem.util.ParamsUtil;
import com.woniu.sharepark.propertysystem.dto.CommunityDTO;
import com.woniu.sharepark.propertysystem.dto.OrderDTO;
import com.woniu.sharepark.propertysystem.pojo.Community;
import com.woniu.sharepark.propertysystem.service.CommunityService;
import com.woniu.sharepark.vo.LayuiDataVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;


/**
 * 小区控制层
 *
 * @author xin
 * @date 2019/6/2 14:58
 * version v1.0
 */
@RequestMapping("/community")
@Controller
public class CommunityController {


    @Resource
    private CarService carService;

    @Resource
    private ScaleService scaleService;

    @Resource
    private CarParkService carParkService;

    @Resource
    private CommunityService communityService;

    @Resource
    private CarParkCommentService carParkCommentService;

    @Resource
    private OrderFormService orderFormService;
    /**
    * 查询当前小区的车位信息
    * @title findAllCarParkPage
    * @param currentPage 当前页
    * @param pageSize 每页数量
    * @return: com.woniu.sharepark.vo.LayuiDataVO<com.woniu.sharepark.leasesystem.lessor.pojo.CarPark>
    * @author xin
    * @date 2019/6/5 19:02
    */
    @RequestMapping("/carPark")
    @ResponseBody
    public LayuiDataVO<CarPark> findAllCarParkPage(@RequestParam("page") Integer currentPage, @RequestParam("limit") Integer pageSize,  CarPark carPark){



        //从session中获取当前小区账号，查询小区id
        Subject subject=SecurityUtils.getSubject();
        Session session= subject.getSession();
        Login login= (Login) session.getAttribute("currentUser");

        Community community=new Community();
        community.setlId(login.getlId());

        community=communityService.findCommunitySelective(community);

        carPark.setComId(community.getComId());


        List<CarPark> list=carParkService.findAllCarParkPage(currentPage,pageSize,carPark);
        PageInfo<CarPark> pageInfo=new PageInfo<>(list);

        // 设置返回的表格数据
        LayuiDataVO<CarPark> layuiDataVO = new LayuiDataVO<>();

        layuiDataVO.setCount( pageInfo.getTotal());
        layuiDataVO.setCode(0);
        layuiDataVO.setData(list);


        return layuiDataVO;

    }


    /**
    * 查询已预订当前小区车位的车辆
    * @title findAllCarPage
    * @param currentPage 当前页
    * @param pageSize 每页数量
    * @return: com.woniu.sharepark.vo.LayuiDataVO<com.woniu.sharepark.leasesystem.tenant.pojo.Car>
    * @author xin
    * @date 2019/6/6 9:53
    */
    @RequestMapping("/car")
    @ResponseBody
    public LayuiDataVO<Car> findAllCarPage(@RequestParam("page") Integer currentPage, @RequestParam("limit") Integer pageSize){


        //从session中获取当前小区账号，查询小区id
        Subject subject=SecurityUtils.getSubject();
        Session session= subject.getSession();
        Login login= (Login) session.getAttribute("currentUser");

        Community community=new Community();
        community.setlId(login.getlId());


        community=communityService.findCommunitySelective(community);

        CarPark carPark=new CarPark();
        carPark.setComId(community.getComId());

        // 查询当前小区已租车位
        carPark.setcState("已租");
        List<CarPark> carParkList=carParkService.findCarParkSelective(carPark);

        Iterator<CarPark> iterator= carParkList.iterator();

        // 拼接所有当前小区已租车位
        StringBuffer cids=new StringBuffer();
        cids.append("(0");

        while (iterator.hasNext()){

            cids.append(",");
            cids.append(iterator.next().getId());


        }
        cids.append(")");


        //根据订单查询租车位的车辆编号
        List<OrderForm> orderFormList=orderFormService.findByCids(cids.toString());

        Iterator<OrderForm> iterator1=orderFormList.iterator();


        StringBuffer carIds=new StringBuffer();
        carIds.append("(0");

        while (iterator1.hasNext()){

            carIds.append(",");
            carIds.append(iterator1.next().getCarId());

        }
        carIds.append(")");

        // 根据车辆id查询车辆信息
        List<Car> carList=carService.findByCarIds(currentPage,pageSize,carIds.toString());


        PageInfo<Car> pageInfo=new PageInfo<>(carList);


        // 设置返回的表格数据
        LayuiDataVO<Car> layuiDataVO = new LayuiDataVO<>();
//
        layuiDataVO.setCount( pageInfo.getTotal());
        layuiDataVO.setCode(0);
        layuiDataVO.setData(carList);



        return layuiDataVO;

    }

    /**
     *@Description: 批量审核车位信息
     *@Param: 车位主键
     *@return: 影响行数
     *@Author: zy
     *@date: 2019/6/10
     */
    @RequestMapping("/check")
    @ResponseBody
    @BackgroundLogAnnotation(operate = "物业审核车位")
    public JsonResult checkCarpark(String params){
        Integer[] ids = ParamsUtil.stringToIntArray(params);

        try {
            int result = carParkService.checkCarparks(ids);
            return JsonResult.ok("成功审核通过"+result+"个车位");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error("审核通过失败");
        }

    }

    /**
    *@Description: 根据登录Id查询对应小区的订单
    *@Param:
    *@return:
    *@Author: zy
    *@date: 2019/6/11
    */
    @RequestMapping("/order")
    @ResponseBody
    public LayuiDataVO<OrderDTO> showOrder(@RequestParam("page") Integer currentPage,
                                           @RequestParam("limit") Integer pageSize,
                                           @RequestParam( value = "lId", required = false)Integer lId){


        //从session中获取当前小区账号，查询小区id
        Subject subject=SecurityUtils.getSubject();
        Session session= subject.getSession();
        Login login= (Login) session.getAttribute("currentUser");
        lId = login.getlId();


       List<OrderDTO> orderList = communityService.findOrderByLId(currentPage,pageSize,lId);

        PageInfo<OrderDTO> pageInfo=new PageInfo<>(orderList);

        // 设置返回的表格数据
        LayuiDataVO<OrderDTO> layuiDataVO = new LayuiDataVO<>();

        layuiDataVO.setCount( pageInfo.getTotal());
        layuiDataVO.setCode(0);
        layuiDataVO.setData(orderList);


        return layuiDataVO;

    }

    /**
    * 查询所有小区渲染地图
    * @title mapList
    * @return: java.util.List<com.woniu.sharepark.propertysystem.pojo.Community>
    * @author SeaMonster
    * @date 2019/6/11 16:25
    */
    @RequestMapping("/mapList")
    @ResponseBody
    public List<Community> mapList(){
        List<Community> list = communityService.findAllCommunityMap();
        return list;
    }


    /**
    * 统计小区车位的状态
    * @title countCarPark
    * @return java.util.Map<java.lang.String,java.lang.Integer>
    * @author xin
    * @date 2019/6/20 15:52
    */
    @RequestMapping("/getTotal")
    @ResponseBody
    public Map<String,Integer> countCarPark(){

        Map<String,Integer> map=new HashMap<String, Integer>(16);
        //从session中获取当前小区账号，查询小区id
        Subject subject=SecurityUtils.getSubject();
        Session session= subject.getSession();
        Login login= (Login) session.getAttribute("currentUser");

        Community community=new Community();
        community.setlId(login.getlId());
        community=communityService.findCommunitySelective(community);

        CarPark carPark=new CarPark();
        CarPark carPark1=new CarPark();
        CarPark carPark2=new CarPark();
        carPark.setComId(community.getComId());
        carPark1.setComId(community.getComId());
        carPark2.setComId(community.getComId());

        List<CarPark> parkList=new ArrayList<CarPark>();

        // 查询该小区车位总数
        parkList=carParkService.findCarParkSelective(carPark);
        map.put("parkTotal",parkList.size());

        // 查询小区未审核车位
        carPark.setcStatus("未通过");
        parkList=carParkService.findCarParkSelective(carPark);
        map.put("unCheckParkCount",parkList.size());

        // 查询小区未租车位
        carPark1.setcState("未租");
        parkList=carParkService.findCarParkSelective(carPark1);
        map.put("unBusyParkCount",parkList.size());


        // 查询小区已租车位

        carPark2.setcState("已租");
        parkList=carParkService.findCarParkSelective(carPark2);
        map.put("busyParkCount",parkList.size());

        return map;
    }


    /**
    * 得到小区的车位评分
    * @title carParkScore
    * @return java.util.Map<java.lang.String,java.lang.Integer>
    * @author xin
    * @date 2019/6/20 16:58
    */
    @GetMapping("/getScore")
    @ResponseBody
    public Map<String,Integer> carParkScore(){

        Map<String,Integer> map=new HashMap<String, Integer>(16);
        //从session中获取当前小区账号，查询小区id
        Subject subject=SecurityUtils.getSubject();
        Session session= subject.getSession();
        Login login= (Login) session.getAttribute("currentUser");

        Community community=new Community();
        community.setlId(login.getlId());
        community=communityService.findCommunitySelective(community);

        CarPark carPark=new CarPark();
        carPark.setComId(community.getComId());


        List<CarPark> carParkList=new ArrayList<CarPark>();

        carParkList=carParkService.findCarParkSelective(carPark);
        Iterator<CarPark> iterator= carParkList.iterator();

        // 拼接所有当前小区车位
        StringBuffer cids=new StringBuffer();
        cids.append("(0");

        while (iterator.hasNext()){

            cids.append(",");
            cids.append(iterator.next().getId());

        }
        cids.append(")");

        List<CarParkComment> parkCommentList=carParkCommentService.selectScoreCount(cids.toString());


        // 统计评分参数

        Integer count0=0;
        Integer count1=0;
        Integer count2=0;
        Integer count3=0;
        Integer count4=0;
        Integer count5=0;

        for (CarParkComment c:parkCommentList
             ) {
            if (c.getCpcScore()==1){
                count1+=1;
            }else if (c.getCpcScore()==2){
                count2+=1;
            }else if (c.getCpcScore()==3){
                count3+=1;
            }else if (c.getCpcScore()==4){
                count4+=1;
            }else if (c.getCpcScore()==5){
                count5+=1;
            } else {
                count0+=1;
            }

        }

        map.put("count0",count0);
        map.put("count1",count1);
        map.put("count2",count2);
        map.put("count3",count3);
        map.put("count4",count4);
        map.put("count5",count5);


        return map;
    }


    /**
    * 得到当前物业的分成
    * @title getMoney
    * @return double
    * @author xin
    * @date 2019/6/20 19:31
    */
    @RequestMapping("/getMoney")
    @ResponseBody
    public double getMoney(){


        //从session中获取当前小区账号，查询小区id
        Subject subject=SecurityUtils.getSubject();
        Session session= subject.getSession();
        Login login= (Login) session.getAttribute("currentUser");

        Community community=new Community();
        community.setlId(login.getlId());
        community=communityService.findCommunitySelective(community);

        CarPark carPark=new CarPark();
        carPark.setComId(community.getComId());


        List<CarPark> carParkList=new ArrayList<CarPark>();

        carParkList=carParkService.findCarParkSelective(carPark);
        Iterator<CarPark> iterator= carParkList.iterator();

        // 拼接所有当前小区车位
        StringBuffer cids=new StringBuffer();
        cids.append("(0");

        while (iterator.hasNext()){

            cids.append(",");
            cids.append(iterator.next().getId());

        }
        cids.append(")");
        List<OrderForm> list=orderFormService.findOrderByCids(cids.toString());
        double money=0.0;



        for (OrderForm o:list
             ) {
            money+=o.getoTotalmoney();
        }
        double scale=0.0;
        scale=scaleService.findScale().getsCommunity();
        money=money*scale;

        BigDecimal bg = new BigDecimal(money).setScale(2, RoundingMode.UP);

        return bg.doubleValue();

    }

    @ResponseBody
    @RequestMapping("/search")
    public List<Community> searchCommunity(CommunityDTO community){
        return communityService.searchCommunity(community);
    }

    @RequestMapping("/add")
    @ResponseBody
    public String add(Community community){
        System.out.println(community);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        Login login = (Login) session.getAttribute("currentUser");
        if (communityService.findComByLid(login.getlId()) != null){
            return "你已经添加了小区，请勿重复添加";
        }
        community.setlId(login.getlId());
        community.setComFlag(0);
        communityService.addCommunity(community);
        return "添加成功";
    }


}
